<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="mmsi序号">
              <a-input v-model="queryParam.mmsiNumber" placeholder="请输入9位mmsi序列号"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              label="开始时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker @change="onBeginChange"
                             :show-time="{ format: 'HH:mm' }"
                             format="YYYY-MM-DD HH:mm"
                             :disabled-date="disabledStartDate"
                             v-model="beginTime"
                             placeholder="开始时间"
              />
            </a-form-item>
          </a-col>

        </a-row>
        <a-row :gutter="48">
          <a-col :md="10" :sm="24">
            <a-form-item
              label="截止时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker @change="onChange"
                             :disabled-date="disabledEndDate"
                             :show-time="{ format: 'HH:mm' }"
                             format="YYYY-MM-DD HH:mm"
                             v-model="endTime"
                             placeholder="结束时间"
              />
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="addTrack()">获取历史轨迹</a-button>
              <a-button style="margin-left: 8px" @click="reset()">重置船舶信息</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="search" @click="handleSearchNew">查询船舶到达港口记录</a-button>
    </div>

    <a-table
      size="default"
      :rowKey="data=>data.trackId"
      :columns="columns"
      :loading="loading"
      :data-source="data"
      :pagination="false"
      @change="handleChange()">
      <!--      @change="handleTableChange"-->
    </a-table>

    <search-ship-track ref="searchShipTrack" :roles="roles" @ok="handleOk" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { queryShipTrack, addShipTrack } from '@/api/ship/shipTrack'
import SearchShipTrack from '@/views/ship/modules/shiptTrack/SearchShipTrack'
import { queryShipPort } from '@/api/ship/shipDetail'

// 用于处理过滤器动态获取数据
let that

export default {
  name: 'ShipTrack',
  components: {
    STable,
    SearchShipTrack
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      beginTime: null,
      endTime: null,
      data: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      loading: false,
      mmsiNumber: '',
      // 查询参数
      queryParam: {},
      // 需要的数据
      roles: [],
      ports: [],
      // 表头
      columns: [
        {
          title: '船舶mmsi序号',
          dataIndex: 'mmsiNumber',
          key: 'mmsiNumber',
          align: 'center'
        },
        {
          title: '港口中文名称',
          dataIndex: 'portChinese',
          key: 'portChinese',
          align: 'center',
        },
        {
          title: '港口英文',
          dataIndex: 'portEnglish',
          key: 'portEnglish',
          align: 'center',
          sorter: false
        },
        {
          title: '港口所属国家或地区',
          dataIndex: 'portCountry',
          key: 'portCountry',
          align: 'center',
          sorter: true
        },
        {
          title: '到港时间',
          dataIndex: 'arriveTime',
          key: 'arriveTime',
          align: 'center',
          sorter: false,
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: '离港时间',
          dataIndex: 'leaveTime',
          key: 'leaveTime',
          align: 'center',
          sorter: false,
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: '停泊时间',
          dataIndex: 'berthingTime',
          align: 'center',
          key: 'berthingTime',
          sorter: true,
          scopedSlots: { customRender: 'date' },
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          }
        },
        {
          title: '离泊时间',
          dataIndex: 'departureTime',
          key: 'departureTime',
          align: 'center',
          sorter: true,
          customRender: (text) => {
            if (text === null) {
              return '-'
            } else {
              return moment(text).format('YYYY-MM-DD HH:mm:ss')
            }
          },
        },
        {
          title: '港口停留(h)',
          dataIndex: 'stayTime',
          key: 'stayTime',
          align: 'center',
          sorter: false
        },
        {
          title: '码头作业(h)',
          dataIndex: 'workTime',
          key: 'workTime',
          align: 'center',
          sorter: false
        },
        {
          title: '靠泊时间(h)',
          dataIndex: 'waitTime',
          key: 'waitTime',
          align: 'center',
          sorter: false
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        // 统一处理查询参数，便于后端表格DTO用固定参数接收
        const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
        return queryShipTrack(Object.assign(parameter, queryJson))
          .then(res => {
            this.loading = false
            return res.result
          })
      },
      optionAlertShow: false
    }
  },
  filters: {
    roleTextFilter (roleId) {
      let roleName = ''
      for (const role of that.roles) {
        if (parseInt(role.id) === parseInt(roleId)) {
          roleName = role.name
          break
        }
      }
      return roleName
    },
    dateTextFilter (departureTime) {
      if (departureTime === null) {
        return '-'
      }
      return departureTime
    },
    statusFilter (key) {
      return key
    }
  },
  beforeCreate() {
    that = this
  },
  created() {
    this.queryTrack()
    queryShipPort()
      .then(res => {
        console.log(res)
        this.ports = res.result
      }).catch(() => {
      this.$message.error('获取港口信息失败')
    })
  },
  methods: {
    handleOk (res) {
        this.data = res
    },
    handleSearchNew () {
      this.$refs.searchShipTrack.search()
      this.$refs.searchShipTrack.ports = this.ports
    },
    addTrack() {
      // _this只是一个变量名，this代表父函数，如果在子函数还用this，this的指向就变成子函数了，_this就是用来存储指向的。
      const _this = this
      _this.loading = true
      const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
      addShipTrack(queryJson)
        .then(res => {
          if (res.result.length !== 0) {
            this.loading = false
            this.$message.success('获取船舶历史轨迹成功')
          } else {
            this.loading = false
            this.$message.error('获取船舶历史轨迹失败')
          }
        }).catch(() => {
          this.loading = false
          this.$message.error('获取船舶历史轨迹失败')
      })
    },
    queryTrack () {
      this.loading = true
      const queryJson = { 'queryParam': JSON.stringify(this.queryParam) }
      queryShipTrack(queryJson)
        .then(res => {
              if (res.result) {
                this.loading = false
                this.data = res.result
              } else {
                this.loading = false
                this.$message.error('查询船舶轨迹失败,没有当前船舶记录')
              }
          }).catch(() => {
          this.loading = false
          this.$message.error('查询船舶轨迹失败')
        })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    onChange (date, dateString) {
      const data1 = this.$moment(date).format('YYYY-MM-DD HH:mm:ss')
      this.queryParam.endTime = data1
    },
    onBeginChange (date, dateString) {
      const data = this.$moment(date).format('YYYY-MM-DD HH:mm:ss')
      this.queryParam.beginTime = data
    },
    disabledStartDate(startValue) {
      const endValue = this.endTime
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    disabledEndDate(endValue) {
      const startValue = this.beginTime
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    reset () {
      this.queryParam = {}
      this.endTime = null
      this.beginTime = null
    },
    handleChange() {
      this.queryTrack()
    }
  }
}
</script>
